package com.sky.aop;

import com.sky.anno.AutoFill;
import com.sky.context.BaseContext;
import com.sky.enumeration.OperationType;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.time.LocalDateTime;

@Slf4j
//把类交给spring管理
@Component
//配置切面类
@Aspect
public class AutoFillAspect {
    @Before("@annotation(com.sky.anno.AutoFill)")
    public void autoFill(JoinPoint joinPoint){
      MethodSignature signature =(MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        AutoFill AutoFill = method.getAnnotation(com.sky.anno.AutoFill.class);
        OperationType operationType = AutoFill.value();
        log.info("自动填充字段为:{}",operationType);
        //获取到方法的参数对象
        Object[] args = joinPoint.getArgs();
        if(args==null || args.length==0){
            log.info("增强方法没有参数对象，无法完成自动填充");
        }
        //获取填充的数据值
        Object entry = args[0];
        Long empId = BaseContext.getCurrentId();
        LocalDateTime now = LocalDateTime.now();
        if (operationType== OperationType.INSERT){
            try {
                //通过反射获取对象中的set方法
                Method setCreateTime = entry.getClass().getDeclaredMethod("setCreateTime", LocalDateTime.class);
                //调用set方法
                setCreateTime.invoke(entry,now);
                Method setCreateUser = entry.getClass().getDeclaredMethod("setCreateUser", Long.class);
                setCreateUser.invoke(entry,empId);
                Method setUpdateTime = entry.getClass().getDeclaredMethod("setUpdateTime", LocalDateTime.class);
                setUpdateTime.invoke(entry,now);
                Method setUpdateUser = entry.getClass().getDeclaredMethod("setUpdateUser", Long.class);
                setUpdateUser.invoke(entry,empId);
            }catch (Exception e){
                log.info("没有找到对应的set方法");
                e.printStackTrace();
            }
        }else {
            try {
                //通过反射获取对象中的set方法
                Method setUpdateTime = entry.getClass().getDeclaredMethod("setUpdateTime", LocalDateTime.class);
                //调用set方法
                setUpdateTime.invoke(entry,now);
                Method setUpdateUser = entry.getClass().getDeclaredMethod("setUpdateUser", Long.class);
                setUpdateUser.invoke(entry,empId);
            }catch (Exception e){
                log.info("没有找到对应的set方法");
                e.printStackTrace();
            }

        }

    }


}
